package handler

import (
	"alarm-flow/handler/pipeline"
	"alarm-flow/pkg/influxdbtool"
	"alarm-flow/utils"
	"fmt"

	"io"
	"log/slog"
	"net/http"
)

var RawDataChan = make(chan []byte, 100)
var EntryChan = make(chan influxdbtool.LineEntry, 100)
var AlarmChan = make(chan pipeline.AlarmEntry, 100)

func init() {
	go influxdbtool.Preprocess(RawDataChan, EntryChan)
	go pipeline.DealEntry(EntryChan, AlarmChan)
	go pipeline.DealAlarm(AlarmChan)
}

func Debug(w http.ResponseWriter, r *http.Request) {
	content := fmt.Sprintf(`
RawDataChan: %d
EntryChan: %d
`, len(RawDataChan), len(EntryChan))

	_, _ = w.Write([]byte(content))
}

func Subscriber(w http.ResponseWriter, r *http.Request) {
	body, err := io.ReadAll(r.Body)
	if err != nil {
		slog.Error("Error reading body:", "error", err)
		return
	}
	defer utils.Close(r.Body)

	RawDataChan <- body
	return
}
